class Playlist < ActiveRecord::Base
  
  #uniq => true is also garanteed through the database(unique index)
  has_many :items, :order => :position, :uniq => true, :class_name => 'PlaylistItem', :conditions => ["played_at IS ? OR playing = ?", nil, true]
  has_many :played_items, :order => :position, :uniq => true, :class_name => 'PlaylistItem', :conditions => ["played_at IS NOT ? AND playing = ?", nil, false]
  has_many :songs, :through => :items, :order => :position, :uniq => true
  
  #Validations
  
  def clear
    items.destroy_all
  end
  
  def number_of_items
    items.length
  end
  
  def current_item
    self.items.find(:first, :conditions => {:playing => true, :position => 1 })
  end
  
  def current_item=(item)
    item.mark_as_current_song
  end
  
  def next_item
    self.items.find(:first, :conditions => ['playing = ?', false])
  end
  
  def previous_item
    return false if not current_item
    return false if current_item.position == 1 #Because current_item.position must be nil!
    
    return self.items.find_by_position(1)
  end
  
  def play_next_item
    current_item.mark_as_played
  end
  
  def find_item_by_file(file)
    self.items.find(:first, :include => :song, :conditions => {'songs.file' => file} )
  end
  
  def sync_with_radio
    MpdCallbacks.sync
  end
end